package com.alibaba.citrus.cr.mn.order.center.facade.function.check;

import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.model.dto.BatchQueryEmployeeByConditionRequest;
import com.epoch.app.mnordercenter.model.dto.Modifiers;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Chen.mu
 * 2023/5/17
 * 校验修改人  订单是否存 等基本校验
 **/
@Component
public class CommonCheck {
    @Resource
    private MnOrderCenterService mnOrderCenterService;

    public Modifiers invalidModifier(String modifierCode) {
        return invalidModifierList(Collections.singletonList(modifierCode)).get(modifierCode);
    }

    public Map<String, Modifiers> invalidModifierList(List<String> modifierCodeList) {
        if (CollectionUtils.isEmpty(modifierCodeList)) {
            return new HashMap<>();
        }
        //修改人查询
        Map<String, Modifiers> modifierMap = getModifiers(modifierCodeList);
        //修改人校验
        modifierCodeList.forEach(modifierCode -> {
            if (!modifierMap.containsKey(modifierCode)) {
                throw new FunctionException("OC-01-001-01-16-041");
            }
            Modifiers modifier = modifierMap.get(modifierCode);
            if (Objects.nonNull(modifier.getStatus()) && modifier.getStatus() != 1) {
                throw new FunctionException("OC-04-004-01-16-007", modifierCode);
            }
        });
        return modifierMap;
    }

    public Map<String, Modifiers> getModifiers(List<String> workIdList) {
        BatchQueryEmployeeByConditionRequest request = new BatchQueryEmployeeByConditionRequest();
        request.setWorkIdList(workIdList);
        Result<List<Modifiers>> listResult = mnOrderCenterService.batchQueryEmployeeByCondition(request);
        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
            return Maps.newHashMap();
        }
        return listResult.getResult().stream()
                .filter(m -> !m.getStatus().equals(-1)) // 过滤掉已删除的数据
                .collect(Collectors.toMap(Modifiers::getWorkId, p -> p, (v1, v2) -> v1));
    }

}
